package com.example.li_han.dao;

import com.example.li_han.pojo.NewsType;
import com.example.li_han.utils.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.example.li_han.utils.ConnUtils.closeResources;

/**
 * 新闻分类数据访问对象类
 */
public class NewsTypeDao {

    /**
     * 获取所有分类列表
     */
    public List<NewsType> getAllNewsTypes() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<NewsType> list = new ArrayList<>();

        try {
            System.out.println("正在连接数据库获取新闻类别...");
            conn = ConnUtils.getConn();

            if (conn == null) {
                System.err.println("数据库连接失败！");
                return list;
            }

            String sql = "SELECT * FROM news_type ORDER BY sortOrder  ASC, typeId ASC";

            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            int count = 0;
            while (rs.next()) {
                NewsType type = new NewsType();
                type.setTypeId(rs.getInt("typeId"));
                type.setTypeName(rs.getString("typeName"));
                type.setSortOrder(rs.getInt("sortOrder"));

                list.add(type);
                count++;
                System.out.println("加载类别: ID=" + type.getTypeId() + ", 名称=" + type.getTypeName());
            }

            System.out.println("从数据库成功加载 " + count + " 个新闻类别");

        } catch (Exception e) {
            System.err.println("获取新闻类别时发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            closeResources(conn, ps, rs);
        }
        return list;
    }

    /**
     * 根据ID获取分类
     */
    public NewsType getNewsTypeById(int typeId) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = ConnUtils.getConn();
            String sql = "SELECT * FROM news_type WHERE typeId = ?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1, typeId);
            rs = pst.executeQuery();

            if (rs.next()) {
                NewsType newsType = new NewsType();
                newsType.setTypeId(rs.getInt("typeId"));
                newsType.setTypeName(rs.getString("typeName"));
                newsType.setSortOrder(rs.getInt("sortOrder"));
                return newsType;
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException("获取分类失败：" + e.getMessage());
        } finally {
            closeResources(conn, pst, rs);
        }
    }

    /**
     * 添加分类
     */
    public int addNewsType(NewsType newsType) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = ConnUtils.getConn();
            String sql = "INSERT INTO news_type (typeName, sortOrder) VALUES (?, ?)";
            pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pst.setString(1, newsType.getTypeName());
            pst.setInt(2, newsType.getSortOrder());

            int result = pst.executeUpdate();

            // 获取自增的主键
            if (result > 0) {
                rs = pst.getGeneratedKeys();
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
            return result;
        } catch (SQLException e) {
            throw new RuntimeException("添加分类失败：" + e.getMessage());
        } finally {
            closeResources(conn, pst, rs);
        }
    }

    /**
     * 更新分类
     */
    public int updateNewsType(NewsType newsType) {
        Connection conn = null;
        PreparedStatement pst = null;
        try {
            conn = ConnUtils.getConn();
            String sql = "UPDATE news_type SET typeName = ?, sortOrder = ? WHERE typeId = ?";
            pst = conn.prepareStatement(sql);
            pst.setString(1, newsType.getTypeName());
            pst.setInt(2, newsType.getSortOrder());
            pst.setInt(3, newsType.getTypeId());
            return pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新分类失败：" + e.getMessage());
        } finally {
            closeResources(conn, pst, null);
        }
    }

    /**
     * 删除分类
     */
    public int deleteNewsType(int typeId) {
        Connection conn = null;
        PreparedStatement pst = null;
        try {
            conn = ConnUtils.getConn();
            String sql = "DELETE FROM news_type WHERE typeId = ?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1, typeId);
            return pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除分类失败：" + e.getMessage());
        } finally {
            closeResources(conn, pst, null);
        }
    }

    /**
     * 检查分类名称是否存在
     */
    public boolean isTypeNameExists(String typeName) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = ConnUtils.getConn();
            String sql = "SELECT COUNT(*) FROM news_type WHERE typeName = ?";
            pst = conn.prepareStatement(sql);
            pst.setString(1, typeName);
            rs = pst.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
            return false;
        } catch (SQLException e) {
            throw new RuntimeException("检查分类名称失败：" + e.getMessage());
        } finally {
            closeResources(conn, pst, rs);
        }
    }

    /**
     * 检查分类是否被新闻使用
     */
    public boolean isTypeInUse(int typeId) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = ConnUtils.getConn();
            String sql = "SELECT COUNT(*) FROM news WHERE typeId = ?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1, typeId);
            rs = pst.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
            return false;
        } catch (SQLException e) {
            throw new RuntimeException("检查分类使用情况失败：" + e.getMessage());
        } finally {
            closeResources(conn, pst, rs);
        }
    }

    /**
     * 关闭数据库资源
     */
    private void closeResources(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}